<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>EventSource连接测试</title>
    <style type="text/css">
        .card-layout {
            margin: auto;
            margin-top: 20px;
            width: 400px;
            background: lightgray;
            padding: 10px;
            border-radius: 10px;
        }

        #name {
            color: red;
            font-size: 18px;
        }

        ul {
            width: 90%;
            height: 70vh;
            background: #62beaa;
            overflow-y: scroll;
            border-radius: 10px;
        }

        li {
            margin-left: 10px;
            font-size: 13px;
            margin-top: 5px;
        }

        li:first-child {
            margin-top: 10px;
        }

        li:last-child {
            margin-bottom: 30px;
        }

        .hor-layout {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .disconnect {
            font-size: 13px;
            color: white;
            background: #6b99ea;
            padding: 3px 8px;
            border-radius: 5px;
        }

        .disconnect:hover {
            background: #296bde;
        }
    </style>

</head>
<body>
<div class="card-layout">
    <p th:text="${hello}">这是的内容将被替换</p>
    <div class="hor-layout">
        <div id="name">姓名：</div>
        <div class="disconnect" onclick="disConnect()">断开</div>
    </div>
    <ul id='content'></ul>
</div>
</body>
</html>
<script>
let eventSource;

window.onload = function () {
  let name = Math.floor(Math.random() * 10000 + 1)
  name = name + '-' + new Date().getTime()
  document.getElementById("name").innerHTML = `姓名：${name}`

  if (typeof (EventSource) !== "undefined") {
    // eventSource = new EventSource("http://localhost:8084/chat/getConnection?nickName=" + name);
    eventSource = new EventSource("/chat/getConnection?nickName=" + name);
    eventSource.onmessage = function (event) {
      console.log("onmessage 收到消息：", event.data)
      let liDom = document.createElement("li")
      liDom.innerHTML = event.data
      document.getElementById("content").appendChild(liDom)
      scrollContent()
    }
    eventSource.addEventListener('error', function (event) {
      console.error("error 错误：" + event);
    });
    eventSource.addEventListener('close', function (event) {
      console.error("close 关闭：" + event);
    });
    eventSource.addEventListener('open', function (event) {
      console.log("open 建立连接：" + event);
    });
  } else {
    document.getElementById("content").innerHTML = "抱歉，您的浏览器不支持 server-sent 事件 ...";
  }
}

function scrollContent() {
  let contentDom = document.getElementById("content")
  contentDom.scrollTop = contentDom.scrollHeight;
}

function disConnect() {
  if (eventSource) {
    eventSource.close();
    console.log("disConnect：断开连接")
    alert("断开连接成功！")
  }
}
</script>
